/*
 * Copyright (c) 2003-2008 jMonkeyEngine
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of 'jMonkeyEngine' nor the names of its contributors 
 *   may be used to endorse or promote products derived from this software 
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.jmex.swt.lwjgl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.swt.widgets.Display;

/**
 * Thread for rendering to a GLCanvas in eclipse.
 * 
 * @author Jochen Mader - jochen@pramari.com - Aug 30, 2008
 * 
 */
public class RenderThread extends Thread {
	/**
	 * Logger for this class.
	 */
	private static final Logger logger = Logger.getLogger(RenderThread.class
			.getName());
	/**
	 * Resuable render runnable.
	 */
	private Runnable renderRunnable;
	/**
	 * SWT display for sync exec.
	 */
	private Display display;
	/**
	 * Shared mutex.
	 */
	private Semaphore mutex;
	/**
	 * List of targets.
	 */
	private ArrayList<LWJGLSWTCanvas> targets;
	/**
	 * Comparator for sorting the targets.
	 */
	private CanvasNextrenderComparator comparator;

	/**
	 * Constructor.
	 * 
	 * @param name
	 *            name for the thread
	 * @param ups
	 *            frames per second
	 * @param mutex
	 *            can be null to iundicate that no other thread is running.
	 */
	public RenderThread(String name, Semaphore mutex, Display display) {
		super(name);
		this.display = display;
		this.mutex = mutex;
		targets = new ArrayList<LWJGLSWTCanvas>();
		comparator = new CanvasNextrenderComparator();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		if (mutex == null) {
			logger.log(Level.INFO,
					"RenderThread started in single thread mode.");
			renderRunnable = new Runnable() {
				private long currTime;

				/*
				 * (non-Javadoc)
				 * 
				 * @see java.lang.Runnable#run()
				 */
				public void run() {
					currTime = System.currentTimeMillis();
					for (LWJGLSWTCanvas canvas : targets) {
						if (currTime >= canvas.getNextrender()) {
							canvas.update();
							canvas.render();
						} else {
							break;
						}
					}
				}

			};
			while (!Thread.interrupted()) {
				if (!display.isDisposed()) {
					display.syncExec(renderRunnable);
					Collections.sort(targets, comparator);
				}
				try {
					Thread.sleep(20);
				} catch (InterruptedException e) {
					// propagate interruption
					Thread.currentThread().interrupt();
				}
			}
		} else {
			logger
					.log(Level.INFO,
							"RenderThread started in multi thread mode.");
			renderRunnable = new Runnable() {
				private long currTime;

				/*
				 * (non-Javadoc)
				 * 
				 * @see java.lang.Runnable#run()
				 */
				public void run() {
					currTime = System.currentTimeMillis();
					for (LWJGLSWTCanvas canvas : targets) {
						if (currTime >= canvas.getNextrender()) {
							canvas.render();
						} else {
							break;
						}
					}
				}
			};
			while (!Thread.interrupted()) {
				if (!display.isDisposed()) {
					try {
						mutex.acquire();
						display.syncExec(renderRunnable);
						Collections.sort(targets, comparator);
					} catch (InterruptedException e) {
						// propagate interruption
						Thread.currentThread().interrupt();
					} finally {
						mutex.release();
					}
				}
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					// propagate interruption
					Thread.currentThread().interrupt();
				}
			}
		}

	}

	public void addTarget(LWJGLSWTCanvas target) {
		targets.add(target);
	}

	public void removeTarget(LWJGLSWTCanvas target) {
		targets.remove(target);
	}

	private class CanvasNextrenderComparator implements
			Comparator<LWJGLSWTCanvas> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
		 */
		public int compare(LWJGLSWTCanvas o1, LWJGLSWTCanvas o2) {
			if (o1.getNextrender() > o2.getNextrender()) {
				return 1;
			}
			if (o1.getNextrender() < o2.getNextrender()) {
				return -1;
			}
			return 0;
		}

	}
}
